#include <QtOpenGL>
#include <QGLWidget>
#include "glviewwidget.h"

GLViewWidget::GLViewWidget(QWidget *parent) :
    QGraphicsView(parent)
{

        QGLWidget *glPort=new QGLWidget(QGLFormat(QGL::SampleBuffers));
        //gl->context()->format().setDoubleBuffer(1);
        setViewport(glPort); //QGLWidget(QGLFormat::defaultFormat(), this)


       //setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing);
       //setOptimizationFlag(QGraphicsView::DontSavePainterState);

       // setFrameShape(NoFrame);
       // setAlignment(Qt::AlignCenter);
       // setCacheMode(QGraphicsView::CacheBackground);
        setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
        //setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
        //setViewportUpdateMode(BoundingRectViewportUpdate);
       // setViewportUpdateMode(FullViewportUpdate);
       // setDragMode(QGraphicsView::RubberBandDrag);
        setDragMode(QGraphicsView::ScrollHandDrag);
       // setTransformationAnchor(AnchorUnderMouse);
       // setResizeAnchor(AnchorViewCenter);
        scaleMap(0.5);


}

void GLViewWidget::scaleMap(qreal scaleFactor)
{
    //if(!state.mapLoaded) return;
    //mapStartDragging();
    //if(config.enableAntialiasing) setRenderHints(NonAntialiasing);

    qreal factor = matrix().scale(scaleFactor, scaleFactor).m11(); //mapRect(QRectF(0, 0, 1, 1)).width();
    qDebug()<< scaleFactor << factor;
    if (factor < qreal(0.01) || factor > qreal(2000)) return;
    scale(scaleFactor, scaleFactor);
}

void GLViewWidget::zoomIn()
{

    setTransformationAnchor(AnchorViewCenter);
    scaleMap(qreal(1.1));
    setTransformationAnchor(AnchorUnderMouse);
}

void GLViewWidget::zoomOut()
{
    setTransformationAnchor(AnchorViewCenter);
    scaleMap(1.0/qreal(1.1));
    setTransformationAnchor(AnchorUnderMouse);
}

void GLViewWidget::fitMap()
{
}

void GLViewWidget::wheelEvent(QWheelEvent *event)
{
scaleMap(pow(qreal(2), event->delta()/qreal(240)));
//    if(event->delta()>0){
//        zoomIn();
//    }else{
//        zoomOut();
//    }

}
